package com.glela.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.glela.common.constant.BaseConstants;
import com.glela.goods.model.DistributaryTemplateDetails;
import com.glela.goods.model.request.DistributaryRequest;
import com.glela.goods.model.response.DistributaryTemplateDetailsResponse;
import com.glela.goods.model.vo.goods.GoodsListResponse;
import com.glela.goods.service.DistributaryService;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.model.User;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.model.response.ResponseResultModel;
import com.glela.platform.service.BaseRestrictionsService;
import com.glela.platform.service.UserService;
import com.glela.platform.util.ParameterUtils;

/**
* @ClassName: DistributaryController 
* @Description: 小铺来了分流入口相关业务Controller
* @author NingChongQing
* @date 2018年3月15日 下午1:52:44
 */
@Controller
@RequestMapping(value = "/distributary")
public class DistributaryController extends BaseController {
	private static Logger logger = LoggerFactory.getLogger(DistributaryController.class);
	
	@Autowired
	private DistributaryService distributaryService;
	@Autowired
	private BaseRestrictionsService baseRestrictionsService;
	@Autowired
	private UserService userService;
	
	/**
	* **********************************************
	* @Title: receivePromotion 
	* @Description: 领取优惠券礼包
	* @param @param request
	* @param @return 
	* @return ResponseEntity<?>
	* @throws	
	* @author NingChongQing	
	* @date 2018年3月15日 下午2:50:01 
	* **********************************************
	 */
	@RequestMapping(value = "/receivePromotion", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> receivePromotion(@RequestBody DistributaryRequest request) {
		try {
			if (ParameterUtils.validParams(request.getUserId(),request.getRedisKey())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			// 礼包ID字符串
			String promotionIdStr = "";
			try {
				promotionIdStr = this.baseRestrictionsService.getBaseRestrictionsForCache(request.getRedisKey()).getName();
			} catch (Exception e) {
				
			}
			int promotionId = Integer.parseInt(promotionIdStr);
			return this.distributaryService.addPromotionByPromotionId(request.getUserId(), promotionId);
		} catch (Exception e) {
			logger.error("领取优惠券礼包异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	
	/**
	* **********************************************
	* @Title: templatePreView 
	* @Description: 模板预览接口 
	* @param @param request
	* @param @return 
	* @return ResponseEntity<?>
	* @throws	
	* @author NingChongQing	
	* @date 2018年3月16日 下午1:47:19 
	* **********************************************
	 */
	@RequestMapping(value = "/templatePreView", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> templatePreView(@RequestBody DistributaryRequest request) {
		try {
			if (ParameterUtils.validParams(request.getTemplateId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			List<DistributaryTemplateDetails> dtdList = this.distributaryService.achieveAvailableTemplateDetails(request.getTemplateId());
			if (CollectionUtils.isEmpty(dtdList)) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C100003), HttpStatus.OK);
			}
			List<DistributaryTemplateDetailsResponse> dtdrList = new ArrayList<DistributaryTemplateDetailsResponse>();
			for (DistributaryTemplateDetails dtd : dtdList) {
				dtdrList.add(new DistributaryTemplateDetailsResponse(dtd));
			}
			Map<String, Object> dtdMap = new HashMap<String, Object>();
			dtdMap.put("templateId", request.getTemplateId());
			dtdMap.put("templateDetails", dtdrList);
			return new ResponseEntity<>(new ResponseResultModel<>(dtdMap), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("模板预览异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	/**
	* **********************************************
	* @Title: tempGoodsList 
	* @Description: 获取临时的商品列表信息 
	* @param @param request
	* @param @return 
	* @return ResponseEntity<?>
	* @throws	
	* @author NingChongQing	
	* @date 2018年3月20日 下午4:26:09 
	* **********************************************
	 */
	@RequestMapping(value = "/tempGoodsList", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> tempGoodsList(@RequestBody DistributaryRequest request) {
		String rslt = null;
		String tempKey = null;
		try {
			if (ParameterUtils.validParams(request.getRedisKey())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			tempKey = StringUtils.EMPTY + request.getRedisKey();
			rslt = queryCacheResult(tempKey);
			if (StringUtils.isEmpty(rslt)) {
				// 商品ID数组
				String tempGoodsIdsStr = "";
				try {
					tempGoodsIdsStr = this.baseRestrictionsService.getBaseRestrictionsForCache(request.getRedisKey()).getName();
				} catch (Exception e) {
					
				}
				Long storeUserId = BaseConstants.XZ_SISTER;
				//显示当前登录或者分享人的店铺信息
				Long showUserId = 0L;
				if (!ParameterUtils.validParams(request.getUserId())) { //当前登录人
					showUserId = Long.valueOf(request.getUserId());
				}
				//没有绑定店主且不是从分享链接查看店主精选商品列表
				if (showUserId.intValue() != 0) {
					User user = this.userService.getUserById(showUserId);
					User storeUser =this.userService.getUserByPersionId(user.getRecommendFrom());
					storeUserId = storeUser.getId();
				}
				List<GoodsListResponse> glrList = new ArrayList<GoodsListResponse>();
				if (!"".equals(tempGoodsIdsStr)) {
					glrList = this.distributaryService.achieveTempGoodsInfo(tempGoodsIdsStr,storeUserId);
				}
				rslt = toResultModelJSON(glrList);
			} else {
				return toRespEntity(rslt);
			}
		} catch (Exception e) {
			logger.error("获取临时的商品列表信息异常", e);
			rslt = toErrorModelJSON(ErrorEnum.C20000);
		}
		// 缓存生效时间120秒钟
		return toRespEntity(toCacheResult(tempKey, rslt, 120));
	}
}
